<template>
  <div>
    <!-- action上传参数地址 -->
    <!-- show-file-list 是否显示上传列表 -->
    <!-- on-success文件上传后的处理 -->
    <!-- before-upload文件上传前的处理 -->
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="uploade"
    >
      <!-- 图片上传成功后，展示的区域 -->
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <!-- 加号图标 -->
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <!-- 进度条 -->
      <el-progress v-show="showProgress" type="circle" :percentage="percentage" class="progress" />
    </el-upload>
  </div>
</template>

<script>
// 导入腾讯云对象存储
var COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDKSKwGK7dsqYy7zauxjESP6WfX8SVHn21',
  SecretKey: 'jBNHvHNBj00jBMGsDH4apnUu2uVptfAO'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      percentage: 0, // 进度条进度
      showProgress: false // 控制进度条的隐藏和显示
    }
  },
  methods: {
    // 图片上传
    uploade(files) {
      // 点击上传显示进度条
      this.showProgress = true
      // 判断上传图片是否存在
      if (files.file) {
        cos.putObject({
          Bucket: 'ayu-1307860568', /* 必须,存储桶的名称 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: files.file.name, /* 必须 对象在存储桶的唯一标识，文件名称*/
          StorageClass: 'STANDARD', // 对象存储类型默认
          Body: files.file, // 上传文件对象
          // 上传的进度
          onProgress: progressData => {
            // 进度条进度
            this.percentage = progressData.percent * 100
          }
          // 上传的回调
        }, (err, data) => {
          if (err === null && data.statusCode === 200) {
            // 将腾讯云返回的地址，赋值给组件src
            this.imageUrl = `https:${data.Location}`
          }
          // 上传成功或失败隐藏进度条
          this.showProgress = false
        })
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 160px;
    height: 160px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
